package com.usian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usian.mapper.TbItemCatmapper;
import com.usian.pojo.TbItemCat;
import com.usian.redis.RedisClient;
import com.usian.service.ItemCategoryService;
import com.usian.utils.CatNode;
import com.usian.utils.CatResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class itemCategoryServiceImpl implements ItemCategoryService {
    @Resource
    TbItemCatmapper tbItemCatmapper;
    @Value("${PROTAL_CATRESULT_KEY}")
    private String PROTAL_CATRESULT_KEY;

    @Autowired
    private RedisClient redisClient;
    /**
     * 查询首页商品分类
     * @return
     */
    @Override
    public CatResult selectItemCategoryAll() {
        //查询缓存
        CatResult catResultRedis =
                (CatResult)redisClient.get(PROTAL_CATRESULT_KEY);
        if(catResultRedis!=null){
            return catResultRedis;
        }
        CatResult catResult = new CatResult();
        //查询商品分类
        catResult.setData(getCatList(0L));
        //添加到缓存
        redisClient.set(PROTAL_CATRESULT_KEY,catResult);
        return catResult;
    }
    /**
     * 私有方法，查询商品分类
     */
    private List<?> getCatList(Long parentId){
        QueryWrapper<TbItemCat> tbItemCatQueryWrapper = new QueryWrapper<>();
        tbItemCatQueryWrapper.eq("status",1);
        tbItemCatQueryWrapper.eq("parent_id",parentId);
        List<TbItemCat> tbItemCats = tbItemCatmapper.selectList(tbItemCatQueryWrapper);
        List resultList = new ArrayList();
        int count = 0;
        for(TbItemCat tbItemCat:tbItemCats){
            //判断是否是父节点
            if(tbItemCat.getIsParent()){
                CatNode catNode = new CatNode();
                catNode.setName(tbItemCat.getName());
                catNode.setItem(getCatList(tbItemCat.getId()));
                resultList.add(catNode);
                count++;
                //只取商品分类中的 18 条数据
                if (count == 18){
                    break;
                }
            }else{
                resultList.add(tbItemCat.getName());
            }

    } return resultList;
    }

}
